package uk.co.agileworks.bidpirate.test;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.jmock.Mockery;
import org.junit.Before;
import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import uk.co.agileworks.bidpirate.web.UserSession;

@Ignore
@ContextConfiguration(loader = SpringTestContextLoader.class, locations = {
		"classpath:spring-test.xml", "file:src/main/webapp/WEB-INF/spring-servlet.xml" })
public class SpringTestBase extends AbstractTransactionalJUnit4SpringContextTests {
	
	protected static final Logger LOGGER = LoggerFactory.getLogger(SpringTestBase.class);

	@Autowired
	protected UserSession userSession;
		
	protected final DataSet dataSet = new DataSet();
	protected final Mockery jMock = new Mockery();

	protected final Model model = new ExtendedModelMap();
	protected final Errors errors = new BeanPropertyBindingResult(dataSet.getBid1(), "bid");

	protected final MockHttpServletRequest request = new MockHttpServletRequest();
	protected final MockHttpServletResponse response = new MockHttpServletResponse();
	
	@Before
	public void setUp() {
		RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
		userSession.logIn(dataSet.getUser1());
	}

	protected void setField(Object target, String fieldName, Object source) {
		Field field = ReflectionUtils.findField(target.getClass(), fieldName);
		field.setAccessible(true);
		ReflectionUtils.setField(field, target, source);
	}
	
	public static Date toDate(String formattedDate) {
		try {
			return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z", Locale.UK).parse(formattedDate);
		} catch (ParseException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
}	
